<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	function check_auth()
	{
		$CI =& get_instance();
	
		//== Check Auth Dummy for Administrator
		if($CI->session->userdata('login')['name'] == "Administrator"){return true;}else{return false;}
		
		
		/*
		
		if(!$cookie = decode_cookies()) return false;
		
		$login_name = $cookie[0];
		$password = $cookie[1];
		
		$query = $CI->db->query("SELECT tblg.GROUP_NAME, tblg.HR_ID, hrs.GENDER, logs.username, logs.PASSWORD 
								FROM LOGINS logs 
								INNER JOIN TBL_GROUPS tblg ON logs.HR_ID = tblg.HR_ID
								INNER JOIN hrs hrs ON hrs.ID = logs.HR_ID
								WHERE 
								logs.USERNAME = '".$login_name."' and PASSWORD = '".$password."'");
		if ($query->num_rows() === 1) 
		{
			$auth = $query->row_array();
			if($auth['LOGIN_NAME'] == $login_name && $auth['PASSWORD'] == $password)
			{
				foreach($auth as $key => $value)
				{
					$GLOBALS[$key] = $value;
				}
				return true;
			}
			else
			{
				return false;
			}
		} 
		else 
		{
			return false;
		}
		*/
	}
	/*=======================================================
	 Function 		: Get All Employee Data
					  from function globals_nik_Search()
	 AUTHOR			: ERY
	 CREATED DATE	: 19/05/2014
	=======================================================*/
	function SearchDetailEmp($Name)
	{	
		$CI =& get_instance();
		$CI->load->model('globals_model');
		$Search_Name = $CI->globals_model->getSearchEmp($Name);
		if ($Search_Name != FALSE)
		{
			foreach($Search_Name AS $Search_Name =>$KeyValue)
			{
				$arr_Name[] = array(
							'ID' =>$KeyValue['ID'], 
							'NAME' =>$KeyValue['NAME']
							);
			}
		}
		else
		{
			$arr_Name[] = array('NAME' => 'No matches found');
		}
		$data['arr_Name'] = $arr_Name;
		return $data;
	}
    //Add by Andi on 29/08/2014
    function SearchDetailEmpGlobal($Name)
	{	
		$CI =& get_instance();
		$CI->load->model('globals_model');
		$Search_Name = $CI->globals_model->getSearchEmpGlobal($Name);
		if ($Search_Name != FALSE)
		{
			foreach($Search_Name AS $Search_Name =>$KeyValue)
			{
				$arr_Name[] = array(
							'ID' =>$KeyValue['ID'], 
							'NAME' =>$KeyValue['NAME']
							);
			}
		}
		else
		{
			$arr_Name[] = array('NAME' => 'No matches found');
		}
		$data['arr_Name'] = $arr_Name;
		return $data;
	}
    //Add by Andi on 15/09/2014
    function SearchDetailRel($Name)
	{	
		$CI =& get_instance();
		$CI->load->model('sGlobal_model');
		$Search_Name = $CI->sGlobal_model->getSearchRel($Name);
		if ($Search_Name != FALSE)
		{
			foreach($Search_Name AS $Search_Name =>$KeyValue)
			{
				$arr_Name[] = array(
							'ID' =>$KeyValue['ID'], 
							'NAME' =>$KeyValue['ID']
							);
			}
		}
		else
		{
			$arr_Name[] = array('NAME' => 'No matches found');
		}
		$data['arr_Name'] = $arr_Name;
		return $data;
	}
    
    //Add By Andi Siswanto on 02-10-2014
    function SearchDetailSer($Name){
        $CI =& get_instance();
		$CI->load->model('sGlobal_model');
		$Search_Name = $CI->sGlobal_model->getSearchSer($Name);
		if ($Search_Name != FALSE)
		{
			foreach($Search_Name AS $Search_Name =>$KeyValue)
			{
				$arr_Name[] = array(
							'ID' =>$KeyValue['ID'], 
							'NAME' =>$KeyValue['ID']
							);
			}
		}
		else
		{
			$arr_Name[] = array('NAME' => 'No matches found');
		}
		$data['arr_Name'] = $arr_Name;
		return $data;
    }
    //Add By Andi Siswanto on 06-10-2014
    function SearchDetailMon($Name){
        $CI =& get_instance();
		$CI->load->model('sGlobal_model');
		$Search_Name = $CI->sGlobal_model->getSearchMon($Name);
		if ($Search_Name != FALSE)
		{
			foreach($Search_Name AS $Search_Name =>$KeyValue)
			{
				$arr_Name[] = array(
							'ID' =>$KeyValue['ID'], 
							'NAME' =>$KeyValue['ID']
							);
			}
		}
		else
		{
			$arr_Name[] = array('NAME' => 'No matches found');
		}
		$data['arr_Name'] = $arr_Name;
		return $data;
    }
    //Add By Andi Siswanto on 21-08-2014
    function SearchDetailVen($Name)
	{	
		$CI =& get_instance();
		$CI->load->model('sGlobal_model');
		$Search_Name = $CI->sGlobal_model->getSearchVen($Name);
		if ($Search_Name != FALSE)
		{
			foreach($Search_Name AS $Search_Name =>$KeyValue)
			{
				$arr_Name[] = array(
							'ID' =>$KeyValue['ID'], 
							'NAME' =>$KeyValue['NAME']
							);
			}
		}
		else
		{
			$arr_Name[] = array('NAME' => 'No matches found');
		}
		$data['arr_Name'] = $arr_Name;
		return $data;
	}
    //=======================================================
	
	/*=======================================================
	 Function 		: Get Employee by Search ID
					  from function globals_nik_detail()
	 AUTHOR			: ERY
	 CREATED DATE	: 19/05/2014
	=======================================================*/
	function putDetailEmp($Nik)
	{
		$CI =& get_instance();
		$CI->load->model('globals_model');
		$data = $CI->globals_model->getDetailEmp($Nik);
		return $data;
	}
    //Add by andi siswanto on 15/09/2014
    function putDetailRel($Relid)
	{
		$CI =& get_instance();
		$CI->load->model('sGlobal_model');
		$data = $CI->sGlobal_model->getDetailRel($Relid);
		return $data;
	}
    //Add by andi siswanto on 21/08/2014
    function putDetailVen($Venid)
	{
		$CI =& get_instance();
		$CI->load->model('sGlobal_model');
		$data = $CI->sGlobal_model->getDetailVen($Venid);
		return $data;
	}
    //Add by andi siswanto on 04/09/2014
    function putDetailFloor($catid)
	{
		$CI =& get_instance();
		$CI->load->model('sGlobal_model');
		$data = $CI->sGlobal_model->getFloorFromCategory($catid);
		return $data;
	}
    //Add by andi siswanto on 10/10/2014 SMS FUNCTION==================================================
    function send_sms($parameter1, $parameter2) {
        $data["app"] = "carols";
        $data["pin"] = "q38gt4ed61a0272cifk83jlf4a180x8m";
        $data["msisdn"] = "$parameter1";
        $data["msg"] = "$parameter2";
        $result = post_it($data, "http://10.1.83.30/sms/send.php");
        //$result = post_it($data, "http://10.2.121.37/sms/send.php");
        //$result = array('');
        //var_dump($result);exit;
        if (isset($result["errno"])) {
            $errno = $result["errno"];
            $errstr = $result["errstr"];
            echo "<B>Error $errno</B> $errstr";
            //exit;
        } else {
            for ($i = 0; $i < count($result); $i++)
                echo $result[$i];
        }
    }
    function post_it($datastream, $url) {
        $url = preg_replace("@^http://@i", "", $url);
        $host = substr($url, 0, strpos($url, "/"));
        $uri = strstr($url, "/");
        $reqbody = "";
        //var_dump($datastream); exit;
        $x=0;
        foreach ($datastream as $key => $val) {
            if (!empty($reqbody)){
                $reqbody.= "&";
            }
            $reqbody.= $key . "=" . urlencode($val);
            
            $bod[$x]=$reqbody;
            //var_dump($bod[$x]);
        }
        //string(10) "app=carols"
        //string(47) "app=carols&pin=q38gt4ed61a0272cifk83jlf4a180x8m"
        //string(66) "app=carols&pin=q38gt4ed61a0272cifk83jlf4a180x8m&msisdn=81219395711"
        //string(86) "app=carols&pin=q38gt4ed61a0272cifk83jlf4a180x8m&msisdn=81219395711&msg=FM+%3A+Tes+Andi"
        //exit;
        $contentlength = strlen($reqbody);
        //echo $contentlength; exit;
        $reqheader = "POST $uri HTTP/1.1\r\n" .
                "Host: $host\n" . "User-Agent: PostIt\r\n" .
                "Content-Type: application/x-www-form-urlencoded\r\n" .
                "Content-Length: $contentlength\r\n\r\n" .
                "$reqbody\r\n";
        //echo $reqheader; exit;
        /* HASILNYA
        POST /sms/send.php HTTP/1.1
        Host: 10.1.83.30
        User-Agent: PostIt
        Content-Type: application/x-www-form-urlencoded
        Content-Length: 86
        
        app=carols&pin=q38gt4ed61a0272cifk83jlf4a180x8m&msisdn=81219395711&msg=FM+%3A+Tes+Andi        
        */        
        
        $socket = fsockopen($host, 80, $errno, $errstr);
        
        //var_dump($socket); exit;
        if (!$socket) {
            $result["errno"] = $errno;
            $result["errstr"] = $errstr;
            return $result;
            //var_dump($result); exit;
        }
    
        fputs($socket, $reqheader);
    
        while (!feof($socket)) {
            $result[] = fgets($socket, 4096);
        }
    
        fclose($socket);
        //var_dump($result); exit;
        return $result;
    } 
    //====================================SMS END==========================================================
    //==
    
	function redirect_auth($cap = '')
	{
		if(!check_auth()) redirect("/login/auth");
		if($cap != '' && !current_user_can($cap))
			if(isset($_SERVER['HTTP_REFERER']))
				redirect($_SERVER['HTTP_REFERER']);
			else
				redirect(site_url("/home"));
	}
	
	function current_user($attr = 'id')
	{
		if(!isset($GLOBALS['user_id']) || is_null($GLOBALS['user_id'])) return null;
		if(array_key_exists($attr, $GLOBALS)) return $GLOBALS[$attr];
		
		$CI =& get_instance();
		$query = $CI->db->query("select $attr from tas_user where user_id = '".$GLOBALS['user_id']."'");
		if($query->num_rows() > 0)
		{
			$row = $query->row_array();
			return $row[$attr];
		}
		else
		{
			return null;
		}
	}
	
	function current_user_can($capabilities = null)
	{
		if($capabilities == null) return false;
		$level = current_user('role');
		if($level == 0) return true; //is the super admin
		
		$CI =& get_instance();
		$query = $CI->db->query("SELECT c.cap_tag 
								 FROM tas_user_roles r 
								 LEFT JOIN tas_user_capabilities c ON c.cap_id = r.cap_id 
								 WHERE r.level_id = '$level' AND c.cap_tag = '$capabilities'"
								 );
		if($query->num_rows() == 0) return false;
		else return true;
	}
	
	function redirect_link($cap = '',$link = '')
	{
		if(!check_auth()) redirect("/login/auth");
		if($cap != '' && !link_user_can($cap, $link))
			if(isset($_SERVER['HTTP_REFERER']))
				redirect($_SERVER['HTTP_REFERER']);
			else
				redirect(site_url("/home"));
	}
	
	function link_user_can($capabilities = null, $link = null)
	{
		if($capabilities == null) return false;
		$level_id = current_user('user_level');
		if($level_id == 0) return true; //is the super admin
		
		$CI =& get_instance();
		$query = $CI->db->query("SELECT add_link,edit_link,delete_link,view_link
								 FROM tas_user_capabilities uc
								 LEFT JOIN (SELECT * from tas_user_roles WHERE tas_user_roles.level_id = $level_id) ur ON uc.cap_id = ur.cap_id
								 WHERE uc.cap_tag = '$capabilities' and $link = 1");
		if($query->num_rows() == 0) return false;
		else return true;
	}
	
	function c_menu($raw, $parent_id = 0)
	{
		$return = array();
		foreach($raw as $key => $val)
		{
			$proceed = FALSE;
			if($raw[$key]['P_PARENT'] == $parent_id)
			{
				$return[$key] = $raw[$key];
				$proceed = TRUE;
			}
			if($proceed) $return[$key]['child'] = c_menu($raw, $raw[$key]['P_ID']);
		}
		return $return;
	}

	function getMenu($is_front = 0)
	{
		$sql = "SELECT FP.P_ID,FP.P_NAME,FP.P_TAG,FP.P_URL,FP.P_PARENT,FP.P_SHOWMENU 
				FROM FM_PRIVILEGES FP INNER JOIN FM_ROLES FR ON FP.P_ID = FR.P_ID WHERE FR.R_ID = 0 ORDER BY FP.P_ID ASC";
		$CI =& get_instance();
		$result = $CI->db->query($sql);
		$return = $result->result_array();
		return c_menu($return);
	}
	
	function createPager($url, $maxpage, $curpage)
	{
		if($maxpage <= 1) return null;
		
		if(substr($url, -1) <> '/') $url = $url.'/';
		
		$ret = '<div class="pager">';
	
		if($curpage > 1)
		{
			$ret.= ' <a href="'.$url.'1" class="first">first</a> ';
			$ret.= ' <a href="'.$url.($curpage - 1).'" class="prev">prev</a> ';
		}else{
			$ret.= ' <span class="first">first</span> ';
			$ret.= ' <span class="prev">prev</span> ';
		}
		
		for($i = $curpage - 5; $i <= $curpage + 5; $i++)
		{
			if($i == $curpage)
				$ret.= '<span class="curpage">'.$curpage.'</span>';
			else if($i > 0 && $i <= $maxpage)
				$ret.= ' <a href="'.$url.$i.'" class="num">'.$i.'</a> ';
		}
		
		if($curpage < $maxpage)
		{
			$ret.= ' <a href="'.$url.($curpage + 1).'" class="next">next</a> ';
			$ret.= ' <a href="'.$url.$maxpage.'" class="last">last</a> ';
		}else{
			$ret.= ' <span class="next">next</span> ';
			$ret.= ' <span class="last">last</span> ';
		}
	
		$ret.= '</div>';
		
		return $ret;
	}
	
	function setMessage($type, $message)
	{
		$CI =& get_instance();
		
		if($type == "success"){ $CI->session->set_userdata('success', $message); }
		else if($type == "warning"){ $CI->session->set_userdata('warning', $message); }
		else if($type == "danger"){ $CI->session->set_userdata('danger', $message); }
	}
?>